package com.xining.official.core.util;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Random;

@SuppressWarnings("all")
public class StringUtil {

    private static final String BLANK = "";


    public static String trim(String str){
        return StringUtil.dealNull(str).trim();
    }

    public static boolean isEmpty(String s){
        return s == null || BLANK.compareTo(s) == 0;
    }
    public static boolean isEmpty(Object str) {
        return str == null || BLANK.equals(str);
    }
    public static boolean isEmpty(Object ...strs){
        for(Object str:strs){
            if(isEmpty(str)){
                return true;
            }
        }
        return false;
    }
    public static String dealNull(String str) {
        return str != null ? str.trim() : BLANK;
    }
    public static String dealNull(String str, String defaultVal) {
        return str != null ? str.trim() : defaultVal;
    }
    public static String dealNull(Object str,String defaultValue){
        return str != null ? str.toString().trim() : defaultValue;
    }
    public static String dealNull(Object obj) {
        String str = BLANK;
        if(obj!=null){
            if(obj instanceof String){
                str = (String)obj;
            }else{
                str = obj.toString();
            }
        }
        return str;
    }


    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');
            if ((i > -1) && (i < (filename.length() - 1))) {
                return filename.substring(i + 1);
            }
        }
        return null;
    }
    public static String getFileName(String filepath){
        if ((filepath != null) && (filepath.length() > 0)) {
            int i = filepath.lastIndexOf('/');
            if ((i > -1) && (i < (filepath.length() - 1))) {
                return filepath.substring(i + 1);
            }
        }
        return filepath;
    }
    public static String getFilePath(String filepath){
        if ((filepath != null) && (filepath.length() > 0)) {
            int i = filepath.lastIndexOf('/');
            if ((i > -1) && (i < (filepath.length() - 1))) {
                return filepath.substring(0,i + 1);
            }
        }
        return filepath;
    }
    public static boolean equals(Object value1, Object value2) {
        boolean is = false;
        if (value1 == value2) { // is null or self
            return is = true;
        }
        if (value1 != null && value2 != null) { // is not null;
            return value1.equals(value2);
        }
        return is;
    }
    public static int random(int n){
        if(n==0) return 0;
        Random random = new Random();
        return Math.abs(random.nextInt())%n;
    }



    public static String createId(Integer length) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    public static String createCode(Integer length) {
        String base = "1234567890";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static String getValueBykeyFromUrl(String url,String key){
        String result = "";
        //redirect_url?code=xxx&portal_server=https://portalserver:port/portal
        //http://5.18.0.1/portal/cloudlogin.html?code=ce321f2cbf344335bafab8776f881591&userip=5.18.0.37&portal_server=http://lvzhou.h3c.com:80/portal/protocol&_ts=1479190177471

        if(url.indexOf('?') != -1){
            url = url.replace('?','&');
        }

        String[] array = url.split("&");
        for(String s : array){
            String[] tem = s.split("=");
            if(tem[0].equals(key)){
                result = tem[1];
                break;
            }
        }

        return result;
    }



    public static String hideWord(String word){
        if(StringUtil.isEmpty(word)){
            return "";
        }
        String src =word;
        String replaceString=null;
        if(word.matches("^.*@.*$")){//邮箱
            src = word.split("@")[0];
            if(src.length()==1){
                replaceString=src;
            }else  if(src.length()<=3){
                replaceString=src.substring(1);
            }else{
                replaceString=src.substring(3);
            }
        }else{
            //至少隐藏两位
            if(src.length()==1){
                replaceString=src;
            }else if(src.length()<=3){
                replaceString=src.substring(1);
            }else{
                int len = src.length();
                int begin = Math.min(len-3, 3);
                int tag = len-3>begin+2?len-3:len-1;
                replaceString=src.substring(begin,tag);
            }
        }

        return word.replaceAll(replaceString, getReplaceChars("*",replaceString.length()));
    }

    private static String getReplaceChars(String replaceChar, int length) {
        String resultReplace = replaceChar;
        for(int i = 1 ; i < length ; i++){
            resultReplace += replaceChar;
        }
        return resultReplace;
    }



    // 13121106865 ->1312110****
    public static String hidePhoneNumber(String phoneNumber){
        return phoneNumber.replaceAll("(\\d*)\\d{4}(\\d{4})","$1****$2");
        // return  phoneNumber.replaceAll("(\\d*)\\d{4}","$1****");
    }
    public static String createFullId(Integer length) {
        String base = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 获取ip地址
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        if  ("127.0.0.1".equals(ip))  {
            // 获取本机真正的ip地址
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
        return ip;
    }

    public static InputStream getInputStreamFromUrl(String path){
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();//url.openConnection();
            conn.setDoInput(true);
            conn.connect();

            return conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void inputstreamtofile(InputStream ins,File file) throws IOException {

        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    }




//    public static void main(String[] args){
//
//        Status.AdviseType type = Status.AdviseType.fromValue("1");
//
//        System.out.println(type.getName());
//    }
}
